package com.tz.controller;

import com.alibaba.fastjson.JSONObject;
import com.tz.domain.Student;
import com.tz.service.StudentService;
import com.tz.utils.ArrayUtil;
import com.tz.utils.RedisUtils;
import com.tz.utils.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * Redis控制器
 *
 * @author lhucstart
 * @create 2021-04-23 13:59
 */
@RestController
public class RedisController {


    @Resource
    private RedisUtils redisUtils;


    @Resource
    private StudentService studentService;


    @GetMapping("/test")
    public String test(String k, String v) {
        redisUtils.set(k, v);
        return (String) redisUtils.get(k);
    }


    @GetMapping("/list")
    public Object list() {
        //step1 先从redis中取
        String strJson = (String) redisUtils.get("studentCache");
        if (StringUtils.isNull(strJson)) {
            System.err.println("从db取值");
            // step2如果拿不到则从DB取值
            List<Student> listStudent = studentService.findStudentList();
            // step3 DB非空情况刷新redis值
            if (!ArrayUtil.isEmpty(listStudent)) {
                redisUtils.set("studentCache", listStudent);
                return listStudent;
            }
            return null;
        } else {
            System.err.println("从redis缓存取值");
            return JSONObject.parseArray(strJson, Student.class);
        }
    }

    @Cacheable(value = "student", key = "#root.methodName")
    @GetMapping("/testCatch")
    public Object testCatch() {
        return studentService.findStudentList();
    }


}
